package cn.fl.institution.controller;

import cmm.mid.core.framework.page.DataResultVO;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstNpBscInfoService;
import cn.fl.customer.vo.CstNpBscInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.framework.constant.DictionaryConstant;
import cn.fl.project.condition.PrjCstAccInfoQueryCondition;
import cn.fl.project.constant.PrjBscInfoConstant;
import cn.fl.project.service.IPrjCstAccInfoService;
import cn.fl.project.vo.PrjCstAccInfoVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Description: 项目基础信息表 控制层 越秀金租
 */
@Controller
@RequestMapping("/institution/yxfl")
public class PrjBscInfoInsYxflController {

    private static final Logger logger = LoggerFactory.getLogger(PrjBscInfoInsYxflController.class);

    @Autowired
    private ICstNpBscInfoService cstNpBscInfoService; // 自然人信息

    @Autowired
    private IPrjCstAccInfoService prjCstAccInfoService;//项目客户基础信息表

    /**
     * 保存 项目客户信息
     */
    @RequestMapping(value = "/saveForYxfl.do", method = RequestMethod.POST)
    @ResponseBody
    public DataResultVO saveForYxfl(HttpServletRequest request) throws BaseException {
        StopWatch stopWatch = new StopWatch("越秀金租采集保存接口计时统计");
        stopWatch.start();
        BaseLogUtils.info(logger, "saveForYxfl", "修改项目客户账户信息及校验入参"+ JSON.toJSONString(request.getParameterMap()), CurrentThreadContext.getCurrentUserName());
        String cstAccInfoId = request.getParameter("cstAccInfoId");//项目客户信息表id
        String insCode = request.getParameter("insCode");//机构code
        String prjId = request.getParameter("prjId");//项目id
        String cstId = request.getParameter("cstId");//客户id
        String cstNm = request.getParameter("cstNm");//客户姓名
        String bkNm = request.getParameter("bkNm");//银行名称
        String bkCd = request.getParameter("bkCd");//银行代码
        String accNo = request.getParameter("accNo");//银行账号
        String mp = request.getParameter("mp");//手机号
        String monthInc = request.getParameter("monthInc");//民族
        String certNo = request.getParameter("certNo");//身份证
        String idAddr = request.getParameter("idAddr");//户籍地
        String postProvince = request.getParameter("rgnPrCd2");//居住地省
        String postCity = request.getParameter("rgnCyCd2");//居住地市
        //文化程度
        String eduLvlCd = request.getParameter("eduLvlCd");
        //居住状况
        String livCndCd = request.getParameter("livCndCd");
        DataResultVO dataResultVO = new DataResultVO(BaseConstant.IS_YESNO_YES, "保存成功");
        try {
            if (StringUtils.isEmpty(prjId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "项目id为空!");
            }
            if (StringUtils.isEmpty(cstId)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户id为空!");
            }
            if (StringUtils.isEmpty(cstNm)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "客户名称为空!");
            }
            if(StringUtils.isEmpty(bkNm) || StringUtils.isEmpty(bkCd)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护开户银行信息!");
            }
            if(StringUtils.isEmpty(monthInc)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护月收入!");
            }
            if(StringUtils.isEmpty(accNo)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护银行卡号!");
            }
            if(StringUtils.isEmpty(mp)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护银行预留手机号!");
            }
            if(StringUtils.isEmpty(postProvince)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护身份证-省!");
            }
            if(StringUtils.isEmpty(postCity)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护身份证-市!");
            }
            if(StringUtils.isEmpty(idAddr)){
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请填写身份证详细地址!");
            }
            if (idAddr.length() > 60) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "身份证详细地址不得超过60字!");
            }
            if (StringUtils.isEmpty(eduLvlCd)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护学历!");
            }
            if (StringUtils.isEmpty(livCndCd)) {
                return new DataResultVO(BaseConstant.IS_YESNO_NO, "请维护居住状况!");
            }
            // 修改居住地-户籍地,月收入
            CstNpBscInfoVO bscInfoVO = this.cstNpBscInfoService.selectById(Long.valueOf(cstId));
            CstNpBscInfoVO cstNpBscInfoVO = new CstNpBscInfoVO();
            if(null != bscInfoVO) {
                boolean flag = false;
                cstNpBscInfoVO.setId(bscInfoVO.getId());
                if (!Objects.equals(bscInfoVO.getIdAddr(), idAddr)) {
                    flag = true;
                    cstNpBscInfoVO.setIdAddr(idAddr);
                }
                if (!Objects.equals(bscInfoVO.getDomicileProvince(), postProvince) || !Objects.equals(bscInfoVO.getDomicleCity(), postCity)) {
                    cstNpBscInfoVO.setDomicileProvince(postProvince);
                    cstNpBscInfoVO.setDomicleCity(postCity);
                    flag = true;
                }
                Long mrIncMoney = DecimalUtils.convertYuanToFen(Double.valueOf(monthInc)); // 月收入转为分
                Double yrInc = DecimalUtils.mul(mrIncMoney.doubleValue(),12d); // 月收入转换年收入
                if (!Objects.equals(bscInfoVO.getYrInc().doubleValue(), yrInc)) {
                    cstNpBscInfoVO.setYrInc(yrInc.longValue());
                    flag = true;
                }
                if (!Objects.equals(eduLvlCd, cstNpBscInfoVO.getEduLvlCd())) {
                    cstNpBscInfoVO.setEduLvlCd(eduLvlCd);
                    flag = true;
                }
                if (!Objects.equals(livCndCd, cstNpBscInfoVO.getLivCndCd())) {
                    cstNpBscInfoVO.setLivCndCd(livCndCd);
                    flag = true;
                }

                if (flag) {
                    cstNpBscInfoVO.setMdfTm(new Date());
                    cstNpBscInfoVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
                }
                BaseLogUtils.info(logger, "saveForYxfl", "修改自然人信息cstNpBscInfoVO"+ JSON.toJSONString(cstNpBscInfoVO), CurrentThreadContext.getCurrentUserName());
                boolean modify = this.cstNpBscInfoService.modify(cstNpBscInfoVO);
                BaseLogUtils.info(logger, "saveForYxfl", "修改自然人信息modify="+ modify, CurrentThreadContext.getCurrentUserName());
            }

            PrjCstAccInfoQueryCondition prjCstAccInfoQueryCondition = new PrjCstAccInfoQueryCondition();
            prjCstAccInfoQueryCondition.setPrjId(Long.valueOf(prjId));
            prjCstAccInfoQueryCondition.setIsDel(BaseConstant.IS_YESNO_NO);
            prjCstAccInfoQueryCondition.setInsCode(PrjBscInfoConstant.PRJ_INS_CODE_YXFL);
            PrjCstAccInfoVO prjCstAccInfo = null;
            List<PrjCstAccInfoVO> prjCstAccInfoVOS = this.prjCstAccInfoService.searchList(prjCstAccInfoQueryCondition);
            BaseLogUtils.info(logger, "saveForYxfl", "越秀金租立项保存 项目基本信息： prjBscInfoVO = " + JSONObject.toJSONString(prjCstAccInfoVOS));
            PrjCstAccInfoQueryCondition condition = new PrjCstAccInfoQueryCondition();
            if (CollectionUtils.isNotEmpty(prjCstAccInfoVOS)) {
                prjCstAccInfo = prjCstAccInfoVOS.get(0);
                if (StringUtils.isNotEmpty(cstAccInfoId)) {
                    condition.setId(Long.valueOf(cstAccInfoId));
                } else if (prjCstAccInfo.getId() != null){
                    condition.setId(prjCstAccInfo.getId());
                }
            }
            condition.setPrjId(Long.valueOf(prjId));
            condition.setCstId(Long.valueOf(cstId));
            condition.setInsCode(insCode);
            condition.setCstNm(cstNm);
            condition.setAccNm(cstNm);
            condition.setBkCd(bkCd);
            condition.setBkNm(bkNm);
            condition.setAccNo(accNo.trim());
            condition.setMp(mp);
            condition.setCertNo(certNo.trim());
            condition.setCertTypCd(DictionaryConstant.CODE_CERT_TYP_CD_0);
            BaseLogUtils.info(logger, "saveForYxfl", "修改项目客户账户信息,condition:"+ JSONObject.toJSONString(condition), CurrentThreadContext.getCurrentUserName());
            dataResultVO = this.prjCstAccInfoService.modifyPrjAccInfo(condition);
            if(BaseConstant.IS_YESNO_YES == dataResultVO.getSuccess()){
                Map<String,String> resultMap = (Map<String, String>) dataResultVO.getData();
                String chkRstCd = resultMap.get("chkRstCd");
                String rstDesc = resultMap.get("rstDesc");
                String bankCardType = resultMap.get("bankCardType");
                //四要素结果
                if (!BaseConstant.IS_YESNO_YES_STR.equals(chkRstCd)) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo(rstDesc);
                    return dataResultVO;
                }
                //银行卡类型
                if (!BaseConstant.IS_YESNO_NO_STR.equals(bankCardType)) {
                    dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
                    dataResultVO.setInfo("不支持此类银行卡，请更换为借记卡");
                    return dataResultVO;
                }
            }
        } catch (BaseException ex) {
            dataResultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            dataResultVO.setInfo(ex.getMessage());
            BaseLogUtils.info(logger, "saveForYxfl", "保存项目客户账户信息及校验,prjId:" + prjId + ".ERROR:" + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
        } catch (Exception e) {
            BaseLogUtils.info(logger, "saveForYxfl", "保存失败，系统异常",CurrentThreadContext.getCurrentUserName(), e);
            return new DataResultVO(BaseConstant.IS_YESNO_NO, "保存失败，系统异常");
        }
        stopWatch.stop();
        BaseLogUtils.info(logger, "saveForYxfl", "保存项目客户账户信息及校验返回dataResultVO=" +
                JSON.toJSONString(dataResultVO) + "-耗时=" + stopWatch.prettyPrint(), CurrentThreadContext.getCurrentUserName());
        return dataResultVO;
    }
}
